package com.chocus.core.service.cms;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.chocus.core.service.cms.StaticPageService;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class StaticPageServiceImpl implements StaticPageService, ServletContextAware {

	/**
	 * freemarker用的配置类
	 */
	private Configuration configuration;

	/**
	 * 注入configurable
	 * 
	 * @param freeMarkerConfigurer
	 */
	public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
		this.configuration = freeMarkerConfigurer.getConfiguration();
	}

	/**
	 * 生成静态模板
	 */
	public void getStaticPage(String id, Map<String, Object> rootMap) {
		String path = getPath("/html/product/" + id + ".html");
		File f = new File(path);
		// 判断父级文件是否存在
		File parentFile = f.getParentFile();
		// 不存在则创建
		if (!parentFile.exists()) {
			parentFile.mkdirs();
		}
		Writer out = null;
		try {
			// 获取模板文件
			Template template = configuration.getTemplate("/productDetail.html");
			// 将文件打为输出流
			out = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
			// 输出数据到文件
			template.process(rootMap, out);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获取部署路径
	 * 
	 * @param name
	 * @return
	 */
	public String getPath(String name) {
		return servletContext.getRealPath(name);
	}

	/**
	 * 保存servletContext
	 */
	private ServletContext servletContext;

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
}
